package user

import (
	"fmt"
	"hong/uniapp_server/common/utils"
	"hong/uniapp_server/resources"
	"mime/multipart"
)

type UserPhotoService struct {
	userPhotoRepository UserPhotoRepository
}

func NewUserPhotoService(userPhotoRepository UserPhotoRepository) *UserPhotoService {
	return &UserPhotoService{
		userPhotoRepository: userPhotoRepository,
	}
}

func (s *UserPhotoService) UploadPhoto(userId int64, file *multipart.FileHeader) (string, error) {
	config := resources.GetYamlConfig()
	var (
		fileName = file.Filename
		region = config.Oss.Region
		bucketName = config.Oss.BucketName
		accessID = config.Oss.AccessID
		accessKey = config.Oss.AccessKey
		objectName = fmt.Sprintf("%d/%s", userId, fileName)
	)

	src, err := file.Open()
	if err != nil {
		return "", err
	}
	defer src.Close()
	// 上传到阿里云OSS
	err = utils.UploadFileToOss(objectName, &src, region, bucketName, accessID, accessKey)
	if err != nil {
		return "", err
	}

	// 保存到数据库
	photo := &UserPhotoEntity{
		UserID: userId,
		FileName: fileName,
		PhotoSize: file.Size,
	}
	err = s.userPhotoRepository.Insert(photo)
	if err != nil {
		return "", err
	}

	return photo.OssPath(region, bucketName), nil
}
